<script setup lang="ts">
import { ref, reactive, watch, h } from "vue";
import { message } from "@/utils/message";
import { deviceDetection } from "@pureadmin/utils";
import { addDialog } from "@/components/ReDialog";
import { zxcvbn } from "@zxcvbn-ts/core";
import { isAllEmpty } from "@pureadmin/utils";
import { ElForm, ElInput, ElFormItem, ElProgress, ElAlert } from "element-plus";
import { updateUserPassword } from "@/api/user";
import { useAccountSettings } from "@/store/modules/useAccountSettings";
import { id } from "element-plus/es/locale/index.mjs";
const { userInfos } = useAccountSettings();
defineOptions({
  name: "AccountManagement"
});

const list = ref([
  {
    title: "账户密码",
    illustrate: "当前密码强度：强",
    button: "修改"
  },
  {
    title: "密保手机",
    illustrate: "已经绑定手机：158****6789",
    button: "修改"
  },
  {
    title: "密保问题",
    illustrate: "未设置密保问题，密保问题可有效保护账户安全",
    button: "修改"
  },
  {
    title: "备用邮箱",
    illustrate: "已绑定邮箱：pure***@163.com",
    button: "修改"
  }
]);

// 密码强度配置
const pwdProgress = [
  { color: "#e74242", text: "非常弱" },
  { color: "#EFBD47", text: "弱" },
  { color: "#ffa500", text: "一般" },
  { color: "#1bbf1b", text: "强" },
  { color: "#008000", text: "非常强" }
];

// 密码表单
const pwdForm = reactive({
  currentPassword: "",
  newPassword: "",
  confirmPassword: ""
});

// 当前密码强度
const curScore = ref(-1);

// 密码正则（密码格式应为8-18位数字、字母、符号的任意两种组合）
const REGEXP_PWD =
  /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)]|[()])+$)(?!^.*[\u4E00-\u9FA5].*$)([^(0-9a-zA-Z)]|[()]|[a-z]|[A-Z]|[0-9]){8,18}$/;

// 监听新密码变化
watch(
  () => pwdForm.newPassword,
  newPwd => {
    curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score;
  }
);

function onClick(item) {
  switch (item.title) {
    case "账户密码":
      openChangePasswordDialog();
      break;
    case "密保手机":
      message("请根据具体业务自行实现", { type: "success" });
      break;
    case "密保问题":
      message("请根据具体业务自行实现", { type: "success" });
      break;
  }
}

// 打开修改密码对话框
function openChangePasswordDialog() {
  addDialog({
    title: "修改密码",
    width: "500px",
    draggable: true,
    closeOnClickModal: false,
    fullscreen: deviceDetection(),
    contentRenderer: () =>
      h("div", { class: "p-4" }, [
        h(ElForm, { model: pwdForm, labelWidth: "100px" }, [
          h(ElFormItem, { label: "当前密码", required: true }, () =>
            h(ElInput, {
              modelValue: pwdForm.currentPassword,
              "onUpdate:modelValue": value => (pwdForm.currentPassword = value),
              type: "password",
              showPassword: true,
              placeholder: "请输入当前密码",
              clearable: true
            })
          ),
          h(ElFormItem, { label: "新密码", required: true }, () =>
            h(ElInput, {
              modelValue: pwdForm.newPassword,
              "onUpdate:modelValue": value => (pwdForm.newPassword = value),
              type: "password",
              showPassword: true,
              placeholder: "请输入新密码",
              clearable: true
            })
          ),
          h(ElFormItem, { label: "确认密码", required: true }, () =>
            h(ElInput, {
              modelValue: pwdForm.confirmPassword,
              "onUpdate:modelValue": value => (pwdForm.confirmPassword = value),
              type: "password",
              showPassword: true,
              placeholder: "请再次输入新密码",
              clearable: true
            })
          )
        ]),
        h("div", { class: "mb-4" }, [
          h("div", { class: "flex justify-between mb-2" }, [
            h("span", {}, "密码强度："),
            h(
              "span",
              { class: "text-sm text-gray-500" },
              curScore.value >= 0 ? pwdProgress[curScore.value]?.text : "未输入"
            )
          ]),
          h(
            "div",
            { class: "flex" },
            pwdProgress.map(({ color }, idx) =>
              h(
                "div",
                {
                  class: "w-[19%]",
                  style: { marginLeft: idx !== 0 ? "1%" : "0" }
                },
                [
                  h(ElProgress, {
                    striped: true,
                    stripedFlow: true,
                    duration: curScore.value === idx ? 6 : 0,
                    percentage: curScore.value >= idx ? 100 : 0,
                    color: color,
                    strokeWidth: 10,
                    showText: false
                  })
                ]
              )
            )
          )
        ]),
        h(ElAlert, {
          title: "密码要求：8-18位数字、字母、符号的任意两种组合",
          type: "info",
          showIcon: true,
          closable: true,
          class: "mb-4"
        })
      ]),
    closeCallBack: () => {
      // 重置表单
      pwdForm.currentPassword = "";
      pwdForm.newPassword = "";
      pwdForm.confirmPassword = "";
      curScore.value = -1;
    },
    beforeSure: done => {
      // 验证表单
      if (!pwdForm.currentPassword) {
        message("请输入当前密码", { type: "warning" });
        return;
      }

      if (!pwdForm.newPassword) {
        message("请输入新密码", { type: "warning" });
        return;
      }

      if (!REGEXP_PWD.test(pwdForm.newPassword)) {
        message("密码格式应为8-18位数字、字母、符号的任意两种组合", {
          type: "warning"
        });
        return;
      }

      if (pwdForm.newPassword !== pwdForm.confirmPassword) {
        message("两次输入的新密码不一致", { type: "warning" });
        return;
      }

      if (pwdForm.currentPassword === pwdForm.newPassword) {
        message("新密码不能与当前密码相同", { type: "warning" });
        return;
      }

      // 这里调用修改密码接口
      updateUserPassword({
        userId: userInfos.id,
        currentPassword: pwdForm.currentPassword,
        newPassword: pwdForm.newPassword
      }).then(res => {
        if (res.success) {
          message("密码修改成功", { type: "success" });
          done();
        } else {
          message(`密码修改失败: ${res.msg}`, { type: "error" });
        }
      });
    }
  });
}
</script>

<template>
  <div
    :class="[
      'min-w-[180px]',
      deviceDetection() ? 'max-w-[100%]' : 'max-w-[70%]'
    ]"
  >
    <h3 class="my-8!">账户管理</h3>
    <div v-for="(item, index) in list" :key="index">
      <div class="flex items-center">
        <div class="flex-1">
          <p>{{ item.title }}</p>
          <el-text class="mx-1" type="info">{{ item.illustrate }}</el-text>
        </div>
        <el-button type="primary" text @click="onClick(item)">
          {{ item.button }}
        </el-button>
      </div>
      <el-divider />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.el-divider--horizontal {
  border-top: 0.1px var(--el-border-color) var(--el-border-style);
}
</style>
